package DBLayer;
import ModelLayer.*;

import java.sql.*;


public class DBPayment {

	private Connection con;
	
	public DBPayment(){
		con = DbConnection1.getInstance().getDBcon();
	}
public Payment findPayment(int paymentID, boolean retriveAssociation)
{
	System.out.print("Hej");
	String wClause = "paymentID = " + paymentID;
	
	return singleWhere(wClause, retriveAssociation);
}

public int insertPayment(Payment pay) throws Exception
{  //call to get the next paymentID number
    int nextPaymentID = GetMax.getMaxId("Select max(ssn) from Payment");
    nextPaymentID = nextPaymentID + 1;
    System.out.println("next ssn = " +  nextPaymentID);

   int rc = -1;
   String query="INSERT INTO Payment(PaymentID, PaymentDate, Amount)  VALUES('"+
  		pay.getPaymentDate()  + "','"  +
	    pay.getAmount()  + "','"  +
        nextPaymentID + "','" +
        pay.getPaymentID() + "',5)";
                 

   System.out.println("insert : " + query);
  try{ // insert new Payment +  dependent
      Statement stmt = con.createStatement();
      stmt.setQueryTimeout(5);
 	  rc = stmt.executeUpdate(query);
      stmt.close();
  }//end try
   catch(SQLException ex){
      System.out.println("Payment ikke oprettet");
      throw new Exception ("Payment is not inserted correct");
   }
   return(rc);
}

private Payment singleWhere(String wClause, boolean retriveAssociation) {
	
	ResultSet results;
	Payment payObj = new Payment();
	
	String query = buildQuery(wClause);
	
	System.out.println(query);
	
	try{
		Statement stmt = con.createStatement();
		stmt.setQueryTimeout(5);
		results = stmt.executeQuery(query);
		
		if(results.next()){
			
			payObj = buildPayment(results);
			stmt.close();
			
			if(retriveAssociation)
			{
				DBSalesOrder dbSalesOrder = new DBSalesOrder();
				SalesOrder so = dbSalesOrder.findSalesOrder(payObj.getPaymentID(), false);
				payObj.setPaymentID(so.getSalesID());
				System.out.println("Payment is selected");
			}
			
		}
	}
		catch(Exception e){
			System.out.println("Query exception:"+e);
		}
		return payObj;
	

}

				
			
		
	
	
	// TODO Auto-generated method stub



private Payment buildPayment(ResultSet results) {
	Payment payObj = new Payment();
	try{
		payObj.setPaymentID(results.getInt("paymentID"));
		payObj.setInvoiceNo(results.getInt("invoiceNo"));
		payObj.setPaymentDate(results.getString("paymentDate"));
		payObj.setAmount(results.getDouble("amount"));
		payObj.setSalesID(results.getInt("salID"));
		
	}
	catch (Exception e)
	{
		System.out.println("error in building the Payment object");
	}
	// TODO Auto-generated method stub
	return payObj;
}
private String buildQuery(String wClause) {
	System.out.print("Hej");
	String query = "select * FROM Payment";
	
	if (wClause.length()>0)
		query=query+" where "+ wClause;
	// TODO Auto-generated method stub
	return query;
}
}